#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>
#include"Common.hpp"

using namespace SocketModule;
using namespace LogModule;

// 服务端主要解决链接的问题，IO的问题，不关心自己未来要传递的信息是什么，不需要关心
using ioserver_t = std::function < void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, ioserver_t service)
        : _port(port), _listensockptr(std::make_unique<TcpSocket>()), _isrunning(false), _service(service)
    {
        _listensockptr->BuiltTcpSocketMethod(_port);
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sockfd = _listensockptr->Accept(&client);
            if(sockfd==nullptr) continue;
            LOG(LogLevel::DEBUG)<<"accept success...";

            //父进程不被阻塞，自动回收进程，避免僵尸
            pid_t id = fork();
            if(id<0)
            {
                LOG(LogLevel::FATAL)<<"fork error...";
                exit(FORK_ERR);
            }
            else if(id==0)
            {
                _listensockptr->Close();
                if(fork()>0) exit(OK);
                //孙子进程在执行任务
                _service(sockfd,client);
                sockfd->Close();
                exit(OK);
            }
            else
            {
                //父进程
                sockfd->Close();
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;
            }
        }
        _isrunning = false;
    }

    ~TcpServer(){}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    ioserver_t _service;
};